import 'dart:async';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:test1/widget/bottom_navigation_bar_input.dart';
import 'package:test1/widget/emoji_text.dart';
import 'package:test1/widget/keyboard_dismiss_on_tap.dart';
import 'package:test1/widget/video_widget.dart';
import 'package:test1/widget/wechat_bubble.dart';
import 'package:loading_more_list/loading_more_list.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'data/WechatMessage.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:extended_text_field/extended_text_field.dart';
import 'package:flutter_plugin_record_plus/flutter_plugin_record.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:video_thumbnail/video_thumbnail.dart';
import 'package:custom_pop_up_menu/custom_pop_up_menu.dart';

class ItemModel {
  String title;
  IconData icon;

  ItemModel(this.title, this.icon);
}

extension FixAutoLines on String {
  String fixAutoLines() {
    return Characters(this).join('\u{200B}');
  }
}

class ChatScreen extends StatefulWidget {
  const ChatScreen({Key? key}) : super(key: key);

  @override
  State<ChatScreen> createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen>
    with SingleTickerProviderStateMixin {
  late Animation<double> animation;
  late AnimationController controller;

  int? selectNum; // 0 表情 1。应用

  late Widget messageChild;

  final wechatMessage = WechatMessageRepository();

  final GlobalKey<ExtendedTextFieldState> _key =
      GlobalKey<ExtendedTextFieldState>();

  final _textEditingController = TextEditingController();

  late double height;

  // 播放声音
  FlutterPluginRecord recordPlugin = new FlutterPluginRecord();

  // 当前路径
  String currentLocalPath = "";

  @override
  void initState() {
    super.initState();

    recordPlugin.responsePlayStateController.listen((data) {
      if (data.playState == "complete") {
        setState(() {
          currentLocalPath = "";
          messageChild = _buildMyWidget();
        });
      }
    });

    height = Platform.isIOS ? 300 : 275;

    controller = AnimationController(
        duration: const Duration(milliseconds: 100), vsync: this);
    animation = Tween(begin: 0.0, end: height).animate(controller)
      ..addListener(() {
        setState(() {});
      });

    messageChild = _buildMyWidget();
  }

  Widget _buildMyWidget() {
    return LoadingMoreList<WechatMessage>(ListConfig<WechatMessage>(
      extendedListDelegate: const ExtendedListDelegate(closeToTrailing: true),
      reverse: true,
      indicatorBuilder: _buildIndicator,
      itemBuilder: (context, WechatMessage item, index) {
        return getItme(item);
      },
      sourceList: wechatMessage,
      physics: const FixedOverscrollBouncingScrollPhysics(),
      padding: const EdgeInsets.all(0.0),
    ));
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return KeyboardDismissOnTap(
      child: Scaffold(
        appBar: AppBar(
          iconTheme: IconThemeData(color: Colors.black),
          elevation: 0.3,
          excludeHeaderSemantics: true,
          backgroundColor: Colors.grey[200],
          centerTitle: true,
          title: const Text("李涛", style: TextStyle(color: Colors.black)),
        ),
        bottomNavigationBar: bottomWidget(),
        body: Column(
          children: [
            Flexible(
                child: InkResponse(
                    onTap: () {
                      FocusScope.of(context).requestFocus(FocusNode());
                      controller.reverse();
                      setState(() {
                        selectNum = 2;
                      });
                    },
                    child: Container(
                      padding: const EdgeInsets.symmetric(horizontal: 10),
                      color: Colors.grey[200],
                      child: messageChild,
                    ))),
            Container(
              margin: EdgeInsets.only(
                  // 避免动画塌陷
                  bottom: ((selectNum == 0 || selectNum == 1) &&
                          animation.value > 50)
                      ? 0
                      : MediaQuery.of(context).padding.bottom),
              child: BottomNavigationBarInput(
                biaoqing: () {
                  FocusScope.of(context).requestFocus(FocusNode());
                  controller.forward();
                  setState(() {
                    selectNum = 0;
                  });
                },
                moreTap: () {
                  FocusScope.of(context).requestFocus(FocusNode());
                  controller.forward();
                  setState(() {
                    selectNum = 1;
                  });
                },
                value: (value) async {
                  wechatMessage.insert(
                      0,
                      WechatMessage(
                          value,
                          true,
                          DateTime.now().millisecondsSinceEpoch,
                          WechatMessageType.text));
                  wechatMessage.setState();
                  await Future.delayed(Duration(milliseconds: 1000));
                  wechatMessage.insert(
                      0,
                      WechatMessage(
                          value,
                          false,
                          DateTime.now().millisecondsSinceEpoch,
                          WechatMessageType.text));
                  wechatMessage.setState();
                },
                textFieldKey: _key,
                textEditingController: _textEditingController,
                hiddenFucntion: () {
                  FocusScope.of(context).requestFocus(FocusNode());
                  controller.reverse();
                  setState(() {
                    selectNum = 2;
                  });
                },
                stopRecord: (path, double audioTimeLength) {
                  wechatMessage.insert(
                      0,
                      WechatMessage(
                          "",
                          true,
                          DateTime.now().millisecondsSinceEpoch,
                          WechatMessageType.voice,
                          localPath: path,
                          duration: audioTimeLength.toInt()));
                  wechatMessage.setState();
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  List<ItemModel> menuItems = [
    ItemModel('复制', Icons.content_copy),
    ItemModel('转发', Icons.send),
    ItemModel('收藏', Icons.collections),
    ItemModel('删除', Icons.delete),
    ItemModel('多选', Icons.playlist_add_check),
    ItemModel('引用', Icons.format_quote),
    ItemModel('提醒', Icons.add_alert),
    ItemModel('搜一搜', Icons.search),
  ];

  Widget _buildLongPressMenu() {
    return ClipRRect(
      borderRadius: BorderRadius.circular(5),
      child: Container(
        width: 220,
        color: const Color(0xFF4C4C4C),
        child: GridView.count(
          padding: EdgeInsets.symmetric(horizontal: 5, vertical: 10),
          crossAxisCount: 5,
          crossAxisSpacing: 0,
          mainAxisSpacing: 10,
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          children: menuItems
              .map((item) => Column(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      Icon(
                        item.icon,
                        size: 20,
                        color: Colors.white,
                      ),
                      Container(
                        margin: EdgeInsets.only(top: 2),
                        child: Text(
                          item.title,
                          style: TextStyle(color: Colors.white, fontSize: 12),
                        ),
                      ),
                    ],
                  ))
              .toList(),
        ),
      ),
    );
  }

  Widget getItme(WechatMessage item) {
    return Container(
      margin: EdgeInsets.only(bottom: 20),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment:
            item.isSelf ? MainAxisAlignment.end : MainAxisAlignment.start,
        children: [
          if (!item.isSelf)
            Container(
              margin: EdgeInsets.only(right: 10),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(6),
                child: Container(
                  width: 40,
                  height: 40,
                  child: CachedNetworkImage(
                    imageUrl:
                        'https://img2.baidu.com/it/u=2421090168,324781765&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
                    placeholder: (context, url) => Container(
                      color: Colors.grey.shade400,
                    ),
                    errorWidget: (context, url, error) =>
                        const Icon(Icons.error),
                  ),
                  // child: Image.network(
                  //     "https://img2.baidu.com/it/u=2421090168,324781765&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500")
                ),
              ),
            ),
          if (item.wechatMessageType == WechatMessageType.image)
            ClipRRect(
              borderRadius: BorderRadius.circular(10),
              child: SizedBox(
                  height: 100,
                  child: AspectRatio(
                    aspectRatio: item.width! / item.height!,
                    child: Image.file(File(item.localPath!), fit: BoxFit.cover,
                        frameBuilder: (BuildContext context, Widget child,
                            int? frame, bool? wasSynchronouslyLoaded) {
                      return Container(
                        color: Colors.grey,
                        child: child,
                      );
                    }),
                  )),
            )
          else if (item.wechatMessageType == WechatMessageType.video)
            ClipRRect(
              borderRadius: BorderRadius.circular(10),
              child: Stack(
                children: [
                  SizedBox(
                      height: 150,
                      child: AspectRatio(
                        aspectRatio: item.width! / item.height!,
                        child:
                            Image.file(File(item.coverUrl!), fit: BoxFit.cover,
                                frameBuilder: (BuildContext context,
                                    Widget child,
                                    int? frame,
                                    bool? wasSynchronouslyLoaded) {
                          return Container(
                            color: Colors.grey,
                            child: child,
                          );
                        }),
                      )),
                  Positioned.fill(
                      child: Container(
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.5),
                    ),
                    child: Icon(Icons.play_circle_outlined,
                        color: Colors.white, size: 40),
                  ))
                ],
              ),
            )
          else
            Builder(builder: (context) {
              return CustomPopupMenu(
                menuBuilder: _buildLongPressMenu,
                barrierColor: Colors.transparent,
                pressType: PressType.longPress,
                child: GestureDetector(
                  onTap: () async {
                    if (item.wechatMessageType == WechatMessageType.voice) {
                      recordPlugin.playByPath(item.localPath!, "file");
                      setState(() {
                        currentLocalPath = item.localPath!;
                        messageChild = _buildMyWidget();
                      });
                    }
                  },
                  child: WechatBubble(
                    direction: !item.isSelf
                        ? WechatBubbleDirection.left
                        : WechatBubbleDirection.right,
                    color: item.isSelf ? Color(0xFF9AED71) : Colors.white,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        if (item.wechatMessageType == WechatMessageType.text)
                          SelectableText(
                            FixAutoLines(item.text).fixAutoLines(),
                            style: TextStyle(
                                color: Colors.black, fontSize: 15, height: 1.5),
                          ),
                        if (item.wechatMessageType == WechatMessageType.voice)
                          Builder(builder: (context) {
                            double maxWidth =
                                MediaQuery.of(context).size.width * 0.7;
                            // 计算宽度比例
                            double widthRatio = item.duration! / 60.0;
                            // 计算实际宽度
                            double actualWidth = maxWidth * widthRatio;
                            print(actualWidth);
                            return Container(
                              width: actualWidth < 70 ? 70 : actualWidth,
                              child: Row(
                                mainAxisAlignment: item.isSelf
                                    ? MainAxisAlignment.end
                                    : MainAxisAlignment.start,
                                // mainAxisSize: MainAxisSize.min,
                                children: [
                                  Offstage(
                                    offstage: item.isSelf,
                                    child: Container(
                                      margin: const EdgeInsets.only(right: 10),
                                      child: currentLocalPath == item.localPath
                                          ? Image.asset(
                                              "asset/message/right_sound.gif",
                                              width: 16,
                                              height: 16,
                                              fit: BoxFit.fill)
                                          : Image.asset(
                                              "asset/message/right_static.png",
                                              width: 16,
                                              height: 16,
                                              fit: BoxFit.fill),
                                    ),
                                  ),
                                  Text(" ${item.duration}″",
                                      style: TextStyle(
                                          fontSize: 15, color: Colors.black)),
                                  Offstage(
                                    offstage: !item.isSelf,
                                    child: Container(
                                      margin: EdgeInsets.only(left: 10),
                                      child: currentLocalPath == item.localPath
                                          ? Image.asset(
                                              "asset/message/left_sound.gif",
                                              width: 16,
                                              height: 16,
                                              fit: BoxFit.fill)
                                          : Image.asset(
                                              "asset/message/left_static.png",
                                              width: 16,
                                              height: 16,
                                              fit: BoxFit.fill),
                                    ),
                                  ),
                                ],
                              ),
                            );
                          })
                      ],
                    ),
                  ),
                ),
              );
            }),
          if (item.isSelf)
            Container(
              margin: const EdgeInsets.only(left: 10),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(6),
                child: SizedBox(
                    width: 40,
                    height: 40,
                    child: CachedNetworkImage(
                      imageUrl:
                          'https://img2.baidu.com/it/u=2421090168,324781765&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
                      placeholder: (context, url) => Container(
                        color: Colors.grey.shade400,
                      ),
                      errorWidget: (context, url, error) => Icon(Icons.error),
                    )),
              ),
            ),
        ],
      ),
    );
  }

  Widget bottomWidget() {
    return Container(
      width: MediaQuery.of(context).size.width,
      height: (animation.value < height && controller.isCompleted)
          ? height
          : animation.value,
      color: Color(0xFFF6F6F6),
      child: ListView(
        children: [
          Container(
            height: selectNum == 0 ? height : 0,
            child: Visibility(
              visible: selectNum == 0,
              maintainState: true,
              maintainSize: true,
              maintainAnimation: true,
              child: biaoqing(),
            ),
          ),
          Container(
            height: selectNum == 1 ? height : 0,
            child: Visibility(
              visible: selectNum == 1,
              maintainState: true,
              maintainSize: true,
              maintainAnimation: true,
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 32),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    InkResponse(
                      onTap: () async {
                        final List<AssetEntity>? result =
                            await AssetPicker.pickAssets(context);
                        if (result == null) {
                          return;
                        }
                        if (result.isNotEmpty) {
                          for (AssetEntity item in result) {
                            if (item.type == AssetType.image) {
                              File? file = await item.file;
                              wechatMessage.insert(
                                  0,
                                  WechatMessage(
                                      "",
                                      true,
                                      DateTime.now().millisecondsSinceEpoch,
                                      WechatMessageType.image,
                                      localPath: file!.path,
                                      height: item.height,
                                      width: item.width));
                              wechatMessage.setState();
                            } else if (item.type == AssetType.video) {
                              File? file = await item.file;

                              final thumbnailPath =
                                  await VideoThumbnail.thumbnailFile(
                                video: file!.path,
                                imageFormat: ImageFormat.JPEG,
                                maxWidth: 1280,
                                quality: 75,
                              );
                              File thumbnailFile = File(thumbnailPath!);
                              wechatMessage.insert(
                                  0,
                                  WechatMessage(
                                      "",
                                      true,
                                      DateTime.now().millisecondsSinceEpoch,
                                      WechatMessageType.video,
                                      localPath: file.path,
                                      height: item.height,
                                      width: item.width,
                                      coverUrl: thumbnailFile.path));
                              wechatMessage.setState();

                              // File? file = await item.file;
                              // wechatMessage.insert(
                              //     0,
                              //     WechatMessage(
                              //         "",
                              //         true,
                              //         DateTime.now().millisecondsSinceEpoch,
                              //         WechatMessageType.video,
                              //         localPath: file!.path,
                              //         height: item.height,
                              //         width: item.width));
                              // wechatMessage.setState();
                            }
                          }
                        }
                      },
                      child: Column(
                        children: [
                          SizedBox(height: 16),
                          Image.asset("asset/message/album.png",
                              width: 54, height: 54, fit: BoxFit.fill),
                          SizedBox(height: 4),
                          Text("照片",
                              style: TextStyle(
                                color: Color(0xFF9999A5),
                                fontSize: 13,
                              )),
                        ],
                      ),
                    ),
                    InkResponse(
                      onTap: () async {},
                      child: Column(
                        children: [
                          SizedBox(height: 16),
                          Image.asset("asset/message/camera.png",
                              width: 54, height: 54, fit: BoxFit.fill),
                          SizedBox(height: 4),
                          Text("相机",
                              style: TextStyle(
                                color: Color(0xFF9999A5),
                                fontSize: 13,
                              )),
                        ],
                      ),
                    ),
                    InkResponse(
                      onTap: () {},
                      child: Column(
                        children: [
                          SizedBox(height: 16),
                          Image.asset("asset/message/conversation.png",
                              width: 54, height: 54, fit: BoxFit.fill),
                          SizedBox(height: 4),
                          Text("通话",
                              style: TextStyle(
                                color: Color(0xFF9999A5),
                                fontSize: 13,
                              )),
                        ],
                      ),
                    ),
                    InkResponse(
                      onTap: () {},
                      child: Column(
                        children: [
                          SizedBox(height: 16),
                          Image.asset("asset/message/transfer.png",
                              width: 54, height: 54, fit: BoxFit.fill),
                          SizedBox(height: 4),
                          Text("转账",
                              style: TextStyle(
                                color: Color(0xFF9999A5),
                                fontSize: 13,
                              )),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget biaoqing() {
    return Stack(
      children: [
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
          height: animation.value,
          child: GridView.builder(
              padding: const EdgeInsets.only(bottom: 40),
              itemCount: ExpressionData.maps.keys.length,
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 7,
                mainAxisSpacing: 15,
                crossAxisSpacing: 25,
              ),
              itemBuilder: (BuildContext context, int index) {
                return InkResponse(
                    onTap: () {
                      String text = ExpressionData.maps.keys.toList()[index];
                      final TextEditingValue value =
                          _textEditingController.value;
                      final int start = value.selection.baseOffset;
                      int end = value.selection.extentOffset;
                      if (value.selection.isValid) {
                        String newText = '';
                        if (value.selection.isCollapsed) {
                          if (end > 0) {
                            newText += value.text.substring(0, end);
                          }
                          newText += text;
                          if (value.text.length > end) {
                            newText +=
                                value.text.substring(end, value.text.length);
                          }
                        } else {
                          newText = value.text.replaceRange(start, end, text);
                          end = start;
                        }

                        _textEditingController.value = value.copyWith(
                            text: newText,
                            selection: value.selection.copyWith(
                                baseOffset: end + text.length,
                                extentOffset: end + text.length));
                      } else {
                        _textEditingController.value = TextEditingValue(
                            text: text,
                            selection: TextSelection.fromPosition(
                                TextPosition(offset: text.length)));
                      }
                      SchedulerBinding.instance
                          .addPostFrameCallback((Duration timeStamp) {
                        _key.currentState?.bringIntoView(
                            _textEditingController.selection.base);
                      });
                    },
                    child: Image.asset(
                        "${ExpressionData.basePath}${ExpressionData.maps[ExpressionData.maps.keys.toList()[index]]}"));
              }),
        ),
        Positioned(
          bottom: 0,
          right: 11,
          child: Container(
            decoration: BoxDecoration(color: Color(0xFFF2F1F6), boxShadow: [
              BoxShadow(
                  color: Color(0xFFF2F1F6),
                  offset: Offset(0, -8.0), //阴影xy轴偏移量
                  blurRadius: 15.0, //阴影模糊程度
                  spreadRadius: 12.0 //阴影扩散程度
                  )
            ]),
            child: Container(
              margin: EdgeInsets.only(bottom: 40),
              child: SafeArea(
                child: Row(
                  children: [
                    SizedBox(width: 20),
                    GestureDetector(
                      onTap: () {
                        String text = _textEditingController.text;
                        if (text.isNotEmpty) {
                          int length = text.length;
                          // 检查文本是否以特殊文本结尾
                          if (text.substring(length - 1, length) == ']') {
                            // 找到特殊文本所在的位置
                            int index = text.lastIndexOf('[');
                            if (index != -1) {
                              // 将特殊文本替换为空字符串
                              _textEditingController.text =
                                  text.replaceRange(index, length, '');
                              return; // 返回退出
                            }
                          }
                          // 最后一个字符不是特殊文本，将最后一个字符替换为空字符串
                          _textEditingController.text =
                              text.substring(0, length - 1);
                          _textEditingController.value = TextEditingValue(
                              text: _textEditingController.text,
                              selection: TextSelection.fromPosition(
                                  TextPosition(
                                      offset:
                                          _textEditingController.text.length)));
                        }
                      },
                      child: Container(
                        width: 50,
                        height: 40,
                        padding: EdgeInsets.symmetric(vertical: 12),
                        decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(5)),
                        child: SvgPicture.asset(
                          "asset/message/删除.svg",
                          color: true ? Colors.black : Color(0xFFe0e0e0),
                        ),
                      ),
                    ),
                    SizedBox(width: 6),
                    GestureDetector(
                      onTap: () async {
                        wechatMessage.insert(
                            0,
                            WechatMessage(
                                _textEditingController.text,
                                true,
                                DateTime.now().millisecondsSinceEpoch,
                                WechatMessageType.text));
                        wechatMessage.setState();
                        _textEditingController.clear();
                      },
                      child: Container(
                        width: 50,
                        height: 40,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            color: true ? Color(0xFF73ba74) : Colors.white,
                            borderRadius: BorderRadius.circular(5)),
                        child: new Text(
                          '发送',
                          style: new TextStyle(
                              color: true ? Colors.white : Color(0xFFe0e0e0),
                              fontSize: 13),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        )
      ],
    );
  }

  bool _isUtf16Surrogate(int value) {
    return value & 0xF800 == 0xD800;
  }

  //you can use IndicatorWidget or build yourself widget
  //in this demo, we define all status.
  Widget _buildIndicator(BuildContext context, IndicatorStatus status) {
    //if your list is sliver list ,you should build sliver indicator for it
    //isSliver=true, when use it in sliver list
    bool isSliver = false;

    Widget widget;
    switch (status) {
      case IndicatorStatus.none:
        widget = Container(height: 0.0);
        break;
      case IndicatorStatus.loadingMoreBusying:
        widget = Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(right: 5.0),
              height: 15.0,
              width: 15.0,
              child: getIndicator(context),
            ),
            Text("正在加载...不要着急")
          ],
        );
        widget = _setbackground(false, widget, 35.0);
        break;
      case IndicatorStatus.fullScreenBusying:
        widget = Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(right: 0.0),
              height: 30.0,
              width: 30.0,
              child: getIndicator(context),
            ),
            Text("正在加载...不要着急")
          ],
        );
        widget = _setbackground(true, widget, double.infinity);
        if (isSliver) {
          widget = SliverFillRemaining(
            child: widget,
          );
        } else {
          widget = CustomScrollView(
            slivers: <Widget>[
              SliverFillRemaining(
                child: widget,
              )
            ],
          );
        }
        break;
      case IndicatorStatus.error:
        widget = Text(
          "好像出现了问题呢？",
        );
        widget = _setbackground(false, widget, 35.0);

        widget = GestureDetector(
          onTap: () {
            // listSourceRepository.errorRefresh();
          },
          child: widget,
        );

        break;
      case IndicatorStatus.fullScreenError:
        widget = Text(
          "好像出现了问题呢？",
        );
        widget = _setbackground(true, widget, double.infinity);
        widget = GestureDetector(
          onTap: () {
            // listSourceRepository.errorRefresh();
          },
          child: widget,
        );
        if (isSliver) {
          widget = SliverFillRemaining(
            child: widget,
          );
        } else {
          widget = CustomScrollView(
            slivers: <Widget>[
              SliverFillRemaining(
                child: widget,
              )
            ],
          );
        }
        break;
      case IndicatorStatus.noMoreLoad:
        // widget = Text("没有更多的了。。不要拖了");
        // widget = _setbackground(false, widget, 35.0);
        widget = SizedBox(
          height: 20,
        );
        break;
      case IndicatorStatus.empty:
        widget = EmptyWidget(
          "这里是空气！",
        );
        widget = _setbackground(true, widget, double.infinity);
        if (isSliver) {
          widget = SliverToBoxAdapter(
            child: widget,
          );
        } else {
          widget = CustomScrollView(
            slivers: <Widget>[
              SliverFillRemaining(
                child: widget,
              )
            ],
          );
        }
        break;
    }
    return widget;
  }

  Widget _setbackground(bool full, Widget widget, double height) {
    widget = Container(
        width: double.infinity,
        height: height,
        child: widget,
        color: Colors.grey[200],
        alignment: Alignment.center);
    return widget;
  }

  Widget getIndicator(BuildContext context) {
    final ThemeData theme = Theme.of(context);
    return theme.platform == TargetPlatform.iOS
        ? const CupertinoActivityIndicator(
            animating: true,
            radius: 16.0,
          )
        : CircularProgressIndicator(
            strokeWidth: 2.0,
            valueColor: AlwaysStoppedAnimation<Color>(theme.primaryColor),
          );
  }
}
